package com.kafka.service;

import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.kafka.dao.IMessageOperation;

/**
 * 会员消费消息
 * 
 * @author 雷洪岸
 * 
 */
@Path("query")
public class QueryResource {
	public static SqlSessionFactory sqlSessionFactory;
	public static Reader reader;
	
	static {
		try {
			reader = Resources.getResourceAsReader("Configuration.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	public String query(@Valid String query) {
		JSONObject json = JSONObject.fromObject(query);
		JSONObject rs = new JSONObject();
		Map<String,String> map = new HashMap<>();
		String messageType = null;
		String status = null;
		int result = 0;
		SqlSession session = sqlSessionFactory.openSession();
		try {
			IMessageOperation messageOperation = session
					.getMapper(IMessageOperation.class);
			if(json.get("messageType")!=null){
				messageType = json.get("messageType").toString();
			}
			if(json.get("status")!=null){
				status = json.get("status").toString();
			}
			map.put("message_type", messageType);
			map.put("status", status);
			result = messageOperation.selectByParam(map);
			rs.put("result", result);
			session.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			session.close();
		}
		return rs.toString();
	}
}
